package com.qn.meta.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qn.core.resources.ResourcesCore;
import com.qn.core.resources.ResourcesHeader;
import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;
/**
 * qingniu-cloud user source analysis
 *
 * @Author: TXG
 * @Date: 2024/6/11
 * @Version V0.0.2
 */
public class VisitorUtil {
    private static final String SEPARATOR=",";
    private static String IPV4_DEFAULT = "127.0.0.1";
    private static String IPV6_DEFAULT = "0:0:0:0:0:0:0:1";
    /**
     * 获取当前网络ip
     */
    
    public static String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader(ResourcesHeader.X_FORWARDED_FOR);
        if (StringUtils.isBlank(ipAddress) || ResourcesCore.UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(ResourcesHeader.PROXY_CLIENT_IP);
        }
        if (StringUtils.isBlank(ipAddress) || ResourcesCore.UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(ResourcesHeader.WL_PROXY_CLIENT_IP);
        }
        if (StringUtils.isBlank(ipAddress) || ResourcesCore.UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(ResourcesHeader.X_REAL_IP);
        }
        if (StringUtils.isBlank(ipAddress) || ResourcesCore.UNKNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (StringUtils.equals(ipAddress.toLowerCase(Locale.ROOT), IPV4_DEFAULT) ||
                    StringUtils.equals(ipAddress.toLowerCase(Locale.ROOT), IPV6_DEFAULT.toLowerCase(Locale.ROOT))) {
                InetAddress inet;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    System.err.println("获取IP失败：" + e.getMessage());
                    return IPV4_DEFAULT;
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (StringUtils.isNotBlank(ipAddress)) {
            if (ipAddress.indexOf(SEPARATOR) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(SEPARATOR));
            }
        }
        return ipAddress;
    }


    /**
     * 获取接受的语言
     */
    public static String getLanguage(HttpServletRequest request) {
        if (request != null) {
            return request.getHeader(ResourcesHeader.ACCEPT_LANGUAGE);
        }
        return "";
    }
    public static String getUserAgents(HttpServletRequest request) {
        if (request != null) {
            return request.getHeader(ResourcesHeader.USER_AGENT);
        }
        return "";
    }

}
